package com.pm.common;

import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import com.pm.common.config.ExcludePath;
import com.pm.common.json.JsonObjectArgResolverHandler;
import com.pm.common.security.AuthenticationInterceptor;
import com.pm.common.security.CurrentUserMethodArgumentResolver;

/**
 * 配置拦截器 Title: InterceptorConfig
 * 
 * @author WuJin
 * @date 2020年1月6日
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

	@Override
	protected void addInterceptors(InterceptorRegistry registry) {
		// 拦截所有请求，判断是否有@UserLogin注解，决定是否需要重新登录
		registry.addInterceptor(userInterceptor()).addPathPatterns("/**")
				.excludePathPatterns(ExcludePath.getExcludePath());
		super.addInterceptors(registry);
	}
	@Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:welcome.html");
    }
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 解决静态资源无法访问
		registry.addResourceHandler("/**").addResourceLocations("classpath:/static/")
				.addResourceLocations("classpath:/templates/");
		// 解决swagger无法访问
		registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/docs.html").addResourceLocations("classpath:/META-INF/resources/");
		// 解决swagger的js文件无法访问
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		registry.addResourceHandler("/examples/**").addResourceLocations("classpath:/META-INF/resources/examples/");
	}

	@Override
	public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
		argumentResolvers.add(currentUserMethodArgumentResolver());
		// 控制器json参数转换
		argumentResolvers.add(jsonObjectArgResolverHandler());
		super.addArgumentResolvers(argumentResolvers);
	}

	@Bean
	public JsonObjectArgResolverHandler jsonObjectArgResolverHandler() {
		return new JsonObjectArgResolverHandler();
	}

	@Bean
	public CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver() {
		return new CurrentUserMethodArgumentResolver();
	}

	@Bean
	public AuthenticationInterceptor userInterceptor() {
		return new AuthenticationInterceptor();
	}
}